from utils.return_data import resultError, resultSuccess
import jwt
from server.settings import JSON_TOKEN_KEY
from user.models import UserProfile


def logging_check(func):
    def wrap(request, *args, **kwargs):
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return resultError('111', '没有token, 请重新登录')

        # 校验jwt
        try:
            token_obj = jwt.decode(token, JSON_TOKEN_KEY, algorithms="HS256")
            # print(token_obj)
            username = token_obj['username']
            user = UserProfile.objects.filter(username=username)
            if len(user) == 1:
                request.myuser = user
            else:
                return resultError('111', '用户查询错误')
        except Exception as e:
            return resultError('111', 'token错误, 请重新登录')

        return func(request, *args, **kwargs)

    return wrap
